package com.edu.modules.comm;

import com.alibaba.fastjson.JSONObject;
import com.sari.common.utils.HttpClient;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class WXData {

    public static String appId = "wxbd3688fcaf9cfa95";

    public static String secret = "a6cd77328865c7320a05527dafe024ef";

    public static String getOpenId(String code){

        JSONObject result = HttpClient.get("https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "secret="+secret+"&appid="+appId+"&grant_type=authorization_code&code="+code);

        return result.getString("openid");
    }

    public static String getToken(){

        JSONObject result = HttpClient.get("https://api.weixin.qq.com/cgi-bin/token?" +
                "grant_type=client_credential&appid="+appId+"&secret="+secret);

        return result.getString("access_token");
    }

    public static String getTicket(String access_token) {

        JSONObject result = HttpClient.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?" +
                "access_token="+ access_token +"&type=jsapi");

        return result.getString("ticket");
    }

    //生成随机字符串UUID
    public static String getUUID(){
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        return uuid;
    }

    //JS-SDK Signature
    public static String getSignature(String url,String ticket,String timeStamp,String nonceStr){

        String str = "jsapi_ticket="+ticket+"&noncestr="+nonceStr+"&timestamp="+timeStamp+"&url=https://open.weixin.qq.com/connect/oauth2/authorize?redirect_uri=https://5151px.com/lekeli/views/ad&appid=wxbd3688fcaf9cfa95&response_type=code&scope=snsapi_base&state="+url;

        String signature = getSha1(str);

        return signature;
    }

    public static String getSha1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}
